package com.dtruth.dataflow.dbmanager;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import com.dtruth.dataflow.util.Env;

/**
 * mysql manager
 * 
 * @author yhl@feheadline.com
 * @date 2014年10月22日
 */
public class MySQLManager {
	private static Logger log = Logger.getLogger(MySQLManager.class);
	// 三属性、四方法

	// 三大核心接口
	private Connection conn = null;
	private PreparedStatement pstmt = null;
	private ResultSet rs = null;

	// 四个方法
	// 创建数据库的连接
	public Connection getConnection() {
		Connection conn = null;
		try {
			Properties pro = Env.getInstance();
			PropertyConfigurator.configure(pro);
			Class.forName(pro.getProperty("mysql.driver"));
			conn = DriverManager.getConnection(pro.getProperty("mysql.url"),
					pro.getProperty("mysql.user"),
					pro.getProperty("mysql.password"));
		} catch (Exception ex) {
			log.error("数据库连接异常:" + ex.toString());
		}
		if (conn == null) {
			log.error("连接无效...");
		}
		return conn;
	}

	// 关闭数据库的方法
	public void closeConn() {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (pstmt != null) {
			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	// 专门用于发送查询语句
	public ResultSet execQuery(PreparedStatement pstmt) throws SQLException {

		// 1、使用Statement对象发送SQL语句
		rs = pstmt.executeQuery();
		// 2、返回结果
		return rs;

	}

	/**
	 * 用于增删改
	 * 
	 * @param pstmt
	 * @param getAutoKey
	 *            ，当为true时，返回插入生成的自增id,否则返回影响的记录数
	 * @return
	 */
	public int execOther(PreparedStatement pstmt, boolean getAutoKey)
			throws SQLException {
		int result = pstmt.executeUpdate();
		if (getAutoKey) {
			ResultSet rs = pstmt.getGeneratedKeys();
			if (rs.next())
				return rs.getInt(1);
		}
		return result;

	}
}
